package com.hy.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.appMedicine.dto.MedicineQueryDTO;
import com.hy.medicine.MedCommonCategory;
import com.hy.medicine.MedicineBasicInfo;
import com.hy.medicine.PrescriptionCategory;
import com.hy.medicine.dto.MedicineSearchDTO;
import com.hy.medicine.vo.MedicineBasicInfoVo;
import com.hy.service.MedCommonCategoryService;
import com.hy.service.MedicineBasicInfoService;
import com.hy.service.PrescriptionCategoryService;
import com.hy.util.Result;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * 药品信息控制器
 */
@RestController
@RequestMapping("/medicineInfo")
@Slf4j
public class MedicineBasicInfoController {

    @Autowired
    private MedicineBasicInfoService medicineBasicInfoService; // 药品信息服务
    @Autowired
    private MedCommonCategoryService medCommonCategoryService; // 通用分类服务
    @Autowired
    private PrescriptionCategoryService prescriptionCategoryService; //

    /**
     * 获取药品信息列表
     */
    @PostMapping("/getMedicineInfo")
    public Result<Serializable> getMedicineInfo(@RequestBody MedicineBasicInfoVo medicineBasicInfoVo) {
        return medicineBasicInfoService.getMedicineInfo(medicineBasicInfoVo);
    }

    /**
     * 导出药品信息
     */
    @PostMapping("/export")
    public void exportMedicine(@RequestBody MedicineBasicInfoVo vo, HttpServletResponse response) {
        try {
            medicineBasicInfoService.exportMedicine(vo,response);
        } catch (Exception e) {
            e.printStackTrace();
            handleExportError(response, e.getMessage());
        }
    }

    /**
     * 导入药品信息
     */
    @PostMapping("/import")
    public Result<Serializable> importMedicine(@RequestParam("file") MultipartFile file) {
        if (file == null) {
            return Result.error("请选择要导入的文件");
        }
        return medicineBasicInfoService.importMedicine(file);
    }

    /**
     * 下载导入模板
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            medicineBasicInfoService.downloadTemplate(response);
        } catch (Exception e) {
            log.error("下载模板失败", e);
            handleExportError(response, e.getMessage());
        }
    }

    /**
     * 搜索药品列表
     */
    @GetMapping("/list")
    @ApiOperation("搜索药品列表")
    public Result search(MedicineSearchDTO dto) {
        return medicineBasicInfoService.searchMedicineList(dto);
    }

    /**
     * 处理导出错误
     */
    private void handleExportError(HttpServletResponse response, String message) {
        try {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> error = new HashMap<>();
            error.put("code", "500");
            error.put("msg", "导出失败：" + message);
            response.getWriter().println(JSON.toJSONString(error));
        } catch (IOException e) {
            log.error("写入错误信息失败", e);
        }
    }


    /**
     * 添加新的药品信息
     *
     * @param medicineBasicInfo 包含需要添加的药品信息的对象，通过请求体传递
     * @return 返回操作结果
     */
    @PostMapping("/add")
    public Result addMedicine(@RequestBody MedicineBasicInfo medicineBasicInfo) {
        return medicineBasicInfoService.addMedicine(medicineBasicInfo);
    }

    /**
     * 更新药品信息
     *
     * @param medicineBasicInfo 包含需要更新的药品信息的对象，通过请求体传递
     * @return 返回操作结果
     */
    @PutMapping("/update")
    public Result updateMedicine(@RequestBody MedicineBasicInfo medicineBasicInfo) {
        return medicineBasicInfoService.updateMedicine(medicineBasicInfo);
    }

    /**
     * 删除药品信息
     *
     * @param medicineBasicInfo 包含药品信息的对象，通过请求体传递
     * @return 返回操作结果
     */
    @DeleteMapping("/delete")
    public Result deleteMedicine(@RequestBody MedicineBasicInfo medicineBasicInfo) {
        return medicineBasicInfoService.deleteMedicine(medicineBasicInfo);
    }

    /**
     * 获取药品详细信息
     *
     * @param medicineId 包含药品信息的对象，通过请求体传递（此处参数似乎不必要）
     * @return 返回药品详细信息的结果
     */
    @GetMapping("/detail/{id}")
    public Result getMedicineDetail(@PathVariable("id") Integer medicineId) {
        return medicineBasicInfoService.getMedicineDetail(medicineId);
    }


    /**
     * 获取通用分类列表
     *
     * @return 返回包含通用分类列表的结果对象，成功或失败
     */
    @GetMapping("/commonCategories")
    public Result getCommonCategories() {
        try {
            // 查询所有通用分类，并按ID升序排序
            List<MedCommonCategory> categories = medCommonCategoryService.list(
                    new LambdaQueryWrapper<MedCommonCategory>()
                            .orderByAsc(MedCommonCategory::getId)
            );
            // 返回包含通用分类列表的成功结果
            return Result.success(categories);
        } catch (Exception e) {
            // 记录获取通用分类列表时发生的异常
            log.error("获取通用分类列表失败", e);
            // 返回错误信息
            return Result.error("获取通用分类列表失败");
        }
    }

    /**
     * 获取处方分类列表
     */
    @GetMapping("/prescriptionCategories")
    public Result getPrescriptionCategories() {
        try {
            List<PrescriptionCategory> categories = prescriptionCategoryService.list(
                    new LambdaQueryWrapper<PrescriptionCategory>()
                            .eq(PrescriptionCategory::getStatus, 1)
                            .orderByAsc(PrescriptionCategory::getId)
            );
            return Result.success(categories);
        } catch (Exception e) {
            log.error("获取处方分类列表失败", e);
            return Result.error("获取处方分类列表失败");
        }
    }


    /**
     * 搜索药品列表
     * @param queryDTO
     * @return
     */
    @PostMapping("/search")
    @ApiOperation("搜索药品列表")
    public Result searchMedicineList(@RequestBody MedicineQueryDTO queryDTO) {

        return medicineBasicInfoService.searchMedicineSockList(queryDTO);
    }

}
